package dmt16.TelemetrySuit.UI
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.geom.Point;
	import flash.html.HTMLLoader;
	import flash.utils.ByteArray;
	
	public class Map extends Sprite
	{
		private var _html:HTMLLoader;
		
		public function Map()
		{
			_html=new HTMLLoader();
			addChild(_html);
			
			_html.addEventListener(Event.COMPLETE,_onPageLoaded);
			_html.loadString(map_html);
		}
		
		private var _loaded:Boolean=false;
		public function get loaded():Boolean
		{
			return _loaded;
		}

		
		private var _mapCentreX:Number=0;
		private var _mapCentreY:Number=0;
		
		private var _userControl:Boolean=false;
		public function get userControl():Boolean
		{
			return _userControl;
		}
		public function set userControl(value:Boolean):void
		{
			_userControl = value;
			if(!value&&_loaded){
				_html.window.setCentre(_mapCentreX,_mapCentreY);
				_html.window.setZoom(16);
			}
			dispatchEvent(new Event(Event.LOCATION_CHANGE));
		}

		
		public override function set width(value:Number):void{
			_html.width=value;
		}
		
		public override function set height(value:Number):void{
			_html.height=value;
		}
				
		private function _onPageLoaded(event:Event):void{
			if(_html.window.map!=null){
				_html.window.map.addListener("dragstart",_onMapDrag);
				_loaded=true;
			}
		}

		private function _onMapDrag():void{
			userControl=true;
		}

		public function drawMapPath(x:Array,y:Array):void{
			if(_loaded){
				_html.window.addPoint(x,y);
				_mapCentreX=x[x.length-1];
				_mapCentreY=y[y.length-1];
				if(!userControl){
					_html.window.setCentre(_mapCentreX,_mapCentreY);
					_html.window.setZoom(16);
				}
			}	
		}
		
		[Embed(source="Assets/map.html",mimeType="application/octet-stream")]
		private static var _file:Class;
		private static var _data:ByteArray;
		private static var map_html:String;
		{
			_data=new _file();
			map_html=_data.readUTFBytes(_data.bytesAvailable);
		}
		
	}
}